package com.lh0811.forge.dependency.security.client.component.annotation;

import com.lh0811.forge.dependency.basic_web.exception.CommonException;
import com.lh0811.forge.dependency.basic_web.response.ServerResponse;
import com.lh0811.forge.dependency.security.client.service.SecurityClient;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;

import java.lang.annotation.Annotation;


@Aspect
@Slf4j
@Component
public class HasACLCodeAop extends AuthAbstractClass {

    @Resource
    private SecurityClient securityClient;


    @Pointcut("@within(com.lh0811.forge.dependency.security.client.component.annotation.HasACLCode) || @annotation(com.lh0811.forge.dependency.security.client.component.annotation.HasACLCode)")
    public void annotationPointCut() {
    }


    @Around("annotationPointCut()")
    public Object around(ProceedingJoinPoint joinPoint) throws Throwable {
        log.debug("进入HasACLCodeAop切面");
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        HasACLCode annotation = signature.getMethod().getAnnotation(HasACLCode.class);
        if (annotation == null) {
            Annotation declaredAnnotation = signature.getDeclaringType().getDeclaredAnnotation(HasACLCode.class);
            if (declaredAnnotation != null) {
                annotation = (HasACLCode) declaredAnnotation;
            }
        }
        String aclCode = annotation.aclCode();
        if (StringUtils.isBlank(aclCode))
            throw CommonException.create(ServerResponse.createByError("使用@HasACLCode注解，必须填写aclCode。"));
        // 获取到当前用户信息
        securityClient.hasACLCode(aclCode);
        Object proceed = joinPoint.proceed(joinPoint.getArgs());
        log.debug("退出HasACLCodeAop切面");
        return proceed;
    }

}
